package com.ming.multifunction.controller;

import com.ming.multifunction.common.BaseResponse;
import com.ming.multifunction.common.ErrorCode;
import com.ming.multifunction.common.ResultUtils;
import com.ming.multifunction.exception.BusinessException;
import com.ming.multifunction.mapper.CommentMapper;
import com.ming.multifunction.model.domain.Comment;
import com.ming.multifunction.model.domain.User;
import com.ming.multifunction.model.request.CommentRequest;
import com.ming.multifunction.model.vo.CommentsVO;
import com.ming.multifunction.service.CommentService;
import com.ming.multifunction.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/comment")
public class CommentController {

    @Resource
    private UserService userService;

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private CommentService commentService;

    @GetMapping("/get")
    public BaseResponse<List<CommentsVO>> listComments(@RequestParam long postId, HttpServletRequest request) {

        if (postId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "帖子不存在");
        }

        List<CommentsVO> comments = commentService.getComments(postId);

        //过滤子级评论，获取父评论
        List<CommentsVO> rootComments = comments.stream().filter(commentsVO -> commentsVO.getParentID() == null).collect(Collectors.toList());

        for (CommentsVO rootComment : rootComments) {
            //找父级评论的子集
            rootComment.setChildren(comments.stream().filter(
                    commentsVO -> rootComment.getId().equals(commentsVO.getParentID())
            ).collect(Collectors.toList()));

        }

        return ResultUtils.success(rootComments);
    }

    @PostMapping("/reply")
    public BaseResponse<Long> bottomComment(@RequestBody CommentRequest commentRequest,HttpServletRequest request){

        if (commentRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"评论参数为空");
        }
        User loginUser = userService.getLoginUser(request);
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentRequest,comment);
        long result=commentService.saveComment(comment,loginUser);
        return ResultUtils.success(result);
    }


}
